# encoding: utf-8
'''
@license: (C) Copyright 2018-2017, Node Supply Chain Manager Corporation Limited.
@contact: 1257309054@qq.com
@file: searchView.py
@time: 2018/8/15 19:05
@author:LDC
'''


from haystack.generic_views import SearchView
from haystack.models import SearchResult

from songcommon.models import Song

from django.core.cache import cache

class MySearchView(SearchView):
    """My custom search view."""

    def get_queryset(self):
        queryset = super(MySearchView, self).get_queryset()
        # further filter queryset based on some set of criteria
        return queryset.all()

    def get_context_data(self, *args, **kwargs):

        # songs = Song.objects.filter(name=kwargs['q'])
        # for song in songs:
        #     print(song.name)
        mySearchView = super(MySearchView, self)

        form_data = mySearchView.get_form_kwargs()['data']
        search_method = form_data['search-method']
        self.ordering = '-playnum'
        context = {}

        print(type(context))
        if search_method == '歌名':
            songs = Song.objects.filter(name__contains = form_data['q']).order_by('-playnum')
            context['object_list'] = songs
            context['search_method'] = 'songname'

        elif search_method == '歌手':
            songs = Song.objects.filter(singer__contains = form_data['q']).order_by('-playnum')
            context['object_list'] = songs
            context['search_method'] = 'singer'

        else:
            context = mySearchView.get_context_data(*args, **kwargs)
            context['search_method'] = 'lyric'

            # context['object_list'] = False
            if not context['object_list']:
                songs = Song.objects.filter(lyric__contains=form_data['q']).order_by('-playnum')

                context['object_list'] = songs
                context['no_whoosh'] = 'no_whoosh'
            else:
                context['object_list'] = sorted(context['object_list'],key=lambda x: x.object.playnum,reverse=True)
            print('context', context)
        cache.set('host:'+self.request.get_host()+'url',self.request.get_host()+self.request.get_full_path(),60*10)
        context['query'] = True if context['object_list'] else False
        return context

